<?php

/**
 * dashboard actions.
 *
 * @package    travis
 * @subpackage dashboard
 * @author     Your name here
 * @version    SVN: $Id: actions.class.php 23810 2009-11-12 11:07:44Z Kris.Wallsmith $
 */
class dashboardActions extends sfActions {

    /**
     * Executes index action
     *
     * @param sfRequest $request A request object
     */
    public function executeIndex(sfWebRequest $request) {
        $this->createData();

        $this->sub = null;
        $this->data = null;
        $h = Doctrine_Core::getTable('tblHotel')->createQuery('s')->select('COUNT(s.id)');
        $this->hotels = $h->fetchOne(array(), Doctrine_Core::HYDRATE_SINGLE_SCALAR);
        $a = Doctrine_Core::getTable('tblUsers')
                ->createQuery('s')
                ->select('COUNT(s.id)')
                ->where('s.permissions=? and s.status=?', array(sbValues::PERMISSIONS_AGENT, sbValues::STATUS_ACTIVE));
        $this->agents = $a->fetchOne(array(), Doctrine_Core::HYDRATE_SINGLE_SCALAR);
        $o = Doctrine_Core::getTable('tblOrders')
                ->createQuery('s')
                ->select('COUNT(s.id)');
        $this->orders = $o->fetchOne(array(), Doctrine_Core::HYDRATE_SINGLE_SCALAR);
        $r = Doctrine_Core::getTable('tblRooms')
                ->createQuery('s')
                ->select('COUNT(s.id)');
        $this->rooms = $r->fetchOne(array(), Doctrine_Core::HYDRATE_SINGLE_SCALAR);

        $ag = new sbAgent();
        $this->reputation = $ag->veryHighReputation();
        $this->day = sbValues::getCurrentDate();
    }

    public function executeLocator(sfWebRequest $request) {
        $latitude = $request->getPostParameter('latitude');
        $longitude = $request->getPostParameter('longitude');
        $limit = $request->getPostParameter('limit');

        if (isset($latitude) && isset($longitude) && isset($limit)) {
            $loc = new sbAgent();
            $possition = $loc->getGeolocationAddress($latitude, $longitude);
            $parsePossition = $loc->parsePossitionAfterGeolocation($possition);
            $agents = $loc->foundAgentsAround($latitude, $longitude, $limit);
            /*Dont print all SHIT with passwords hash*/
            $new_agents=Array();
            foreach($agents as $agt)
                {
                $new_agents[]=array('title'=>$agt['title'],
                                    'reputation'=>$agt['reputation'],
                                    'orders'=>$agt['orders'],
                                    'id'=>$agt['id']);
                }
            die(json_encode(array('possition' => $parsePossition, 'agents' => $new_agents)));
        } else {
            die(json_encode('incorrect values'));
        }
    }

    public function executeAgentsLocator(sfWebRequest $request) {
       
        $this->createData();
        $this->sub = null;

        $latitude = $request->getParameter('lt');
        $longitude = $request->getParameter('ln');
        $sort = $request->getParameter('sort');
        if (is_null($sort)) {
            $sort = 1; //my location
            $this->search = array('data' => false, 'country' => 0, 'region' => 0, 'city' => 0);
        } else {
            $country = $request->getParameter('country');
            $region = $request->getParameter('region');
            $city = $request->getParameter('city');
            $this->search = array('data' => true, 'country' => $country, 'region' => $region, 'city' => $city);
        }

        $loc = new sbAgent();
        
        $this->selectCountry = $loc->allCountry();
        $this->selectRegion = $loc->allRegions();
        $this->selectCity = $loc->allCity();

        if (isset($latitude) && isset($longitude)) {
            if ($sort == 1) {
                $points = $loc->foundAgentsAround($latitude, $longitude, 30);
                $this->maps = array('latitude' => $latitude, 'longitude' => $longitude);
                $this->arrAgents = $points;
            } else {
                $points = $loc->sortAgents($country, $region, $city);
                $this->maps = $loc->findMapPosition($country, $city);
                $this->arrAgents = $points;
            }

            $this->myLatitude = $latitude;
            $this->myLongitude = $longitude;

            if ($points) {
                $this->arrRegion = $loc->foundAgentsByRegions($points[0]['region'], 30);
                $this->arrCountry = $loc->foundAgentsByCountry($points[0]['country'], 30);
            }
        } else {
            $this->redirect('homepage');
        }
    }

    public function executeRequestAgent(sfWebRequest $request) {
        $this->setLayout('loginLayout');
        $this->createData();
        $this->sub = null;

        $agent_id = $request->getParameter('agent');
        $this->agent_id = $agent_id;

        $this->form = new RequestToAgentForm();
        if ($request->isMethod('post')) {
            $loc = new sbAgent();
            $mail = $loc->sendMailToAgent($request->getParameter('messages'), $agent_id);

            if ($mail) {
                $this->redirect('agentpage', array('agent' => $agent_id));
            }
        }
    }

    public function executeLoginUser(sfWebRequest $request) {
        $this->setLayout('loginLayout');
        $this->createData();
        $this->sub = null;
        $this->data = null;

        $this->form = new LoginForm();
        $this->error = " ";

        $this->getResponse()->setCookie("ttroli", base64_encode($request->getReferer()));

        if ($request->isMethod('post')) {
            $login = $request->getParameter('logins');
            $result = sbUser::userLogin($login['username'], $login['password']);
            if (!is_null($result)) {
                if (isset($login['stay'])) {
                    $stay = 'online';
                } else {
                    $stay = 'offline';
                }
                $data = $result->getEmail() . "/" . $result->getPermissions() . "/" . $result->getId() . "/" . time() . "/" . $stay;
                $this->getResponse()->setCookie("troli", base64_encode($data));
                $prevPage = base64_decode($this->getRequest()->getCookie("ttroli"));
                $this->getResponse()->setCookie("ttroli", "");
                if (!is_null($prevPage)) {
                    $this->redirect($prevPage);
                } else {
                    $this->redirect('homepage');
                }
            } else {
                $this->error = "Incorrect username or password.";
            }
        }
    }

    public function executeResetPasswordUser(sfWebRequest $request) {
        $this->setLayout('loginLayout');
        $this->createData();
        $this->sub = null;
        $this->data = null;

        $this->form = new ResetPasswordForm();
        $this->error = "";

        if ($request->isMethod('post')) {
            $email = $request->getParameter('resets');
            $result = sbUser::resetPassword($email['email']);
            if ($result == sbValues::PASSWORT_RESET_SUCCSESS) {
                $this->redirect('forgotok');
            } else {
                $this->error = 'In our database, there is no user with the address ' . $email['email'] . '.';
            }
        }
    }

    public function executePasswordReset(sfWebRequest $request) {
        $this->setLayout('loginLayout');
        $this->createData();
        $this->sub = null;
        $this->data = null;

        $this->success = "At this address, we sent an email with instructions.";
    }

    public function executeLogout(sfWebRequest $request) {
        $this->name = null;
        $this->menu = null;
        $this->getResponse()->setCookie("troli", "");
        $this->redirect('homepage');
    }

    public function executeHotels(sfWebRequest $request) {
        $this->createData();
        $this->permisssions = $this->getPermissions();
        $this->sub = 'Hotels';

        $this->city = Doctrine_Core::getTable('tblCity')->createQuery('a')->execute();
        $this->names = Doctrine_Core::getTable('tblHotel')->createQuery('a')->execute();

        $sort = $request->getParameter('sort');
        if (is_null($sort)) {
            $sort = 'price';
        }

        $page = $request->getParameter('page');
        if (is_null($page)) {
            $page = 1;
        }
        
        $type = $request->getParameter('type');
        if (is_null($type)) {
            $type = sbValues::TOURIST;
        }

        $city_id = $request->getParameter('city_id');
        $hotel_id = $request->getParameter('hotel_id');
        if (isset($city_id) && isset($hotel_id)) {
            $search = array(
                'date' => $request->getParameter('date'),
                'night' => $request->getParameter('night'),
                'stars' => $request->getParameter('stars'),
                'civic' => $request->getParameter('type'),
                'rooms' => $request->getParameter('rooms')
            );
        } else {
            $search = array(
                'date' => sbValues::getDateToDB(),
                'night' => 1,
                'stars' => '1,5',
                'civic' => sbValues::TOURIST,
                'rooms' => '1:2:0:0;'
            );
        }

        $searchHotels = new newHotelSearch();
        if (isset($city_id) && isset($hotel_id) && isset($search['date']) && isset($search['rooms'])) {
            $hotels = $searchHotels->searchHotels($city_id, $hotel_id, $search['date'], $search['night'], $search['rooms'], $search['stars'], $search['civic']);
            $this->hotels = $searchHotels->returnsHotelsToPage($page, $hotels);
            $this->pages = $searchHotels->afterSearchPages(count($hotels));
            $this->page = 1;
            $this->sort = 'rank';
        } else {
            $this->hotels = $searchHotels->checkSort($sort, $page);
            $this->pages = $searchHotels->allAvailableHotels();
            $this->page = $page;
            $this->sort = $sort;
        }

        $this->search = $search;
        $this->sorts = $searchHotels->allSorts();
    }

    public function executeHotel(sfWebRequest $request) {
        $this->createData();
        $this->permisssions = $this->getPermissions();
        $this->sub = 'Hotels';

        $hotel_id = $request->getParameter('id');
        $date = $request->getParameter('date');
        if (is_null($date)) {
            $date = sbValues::getDateToDB();
        }
        $night = $request->getParameter('night');
        if (is_null($night)) {
            $night = 1;
        }
        $type = $request->getParameter('type');
        if (is_null($type)) {
            $type = sbValues::TOURIST;
        }

        $this->search = array(
            'rooms' => $request->getParameter('rooms')
        );
        $this->hotel = sbHotels::searchHotel($hotel_id, $date, $night, $type);
        $this->date_from = $date;
        $timestamp = strtotime($date) + ($night * 24 * 60 * 60);
        $this->date_to = date("Y-m-d", $timestamp);
        $this->type = $type;
    }

    public function executeBooking(sfWebRequest $request) {
        $this->createData();
        $this->sub = 'Hotels';

        $hotel_id = $request->getParameter('hotel');
        $type = $request->getParameter('type');
        $date = $request->getParameter('date');
        $night = $request->getParameter('night');
        $rooms_id = $request->getParameter('id');
        $counts = $request->getParameter('counts');
        $rooms = $request->getParameter('rooms');
        $session = $request->getParameter('session');
        $price = $request->getParameter('price');

        $booking = new sbBooking();
        $this->info = $booking->info($hotel_id, $rooms_id, $counts, $session);
        $this->guest = $booking->parseGuests($rooms);
        $this->payments = $booking->payment($this->getMyId());
        $this->date = array('in' => $date, 'out' => date('Y-m-d', strtotime($date . '+' . $night . 'days')), 'days' => $night);
        $parsePrice = explode(';', $price);
        $newPrice = 0;
        for ($i = 0; $i < count($parsePrice); $i++) {
            $newPrice = $newPrice + $parsePrice[$i];
        }
        $this->price = $newPrice;
    }

    public function executeRequestBooking(sfWebRequest $request) {
        $id = $this->getMyId();
        $post = $request->getPostParameters();

        $booking = new sbBooking();
        $result = $booking->requestBooking($id, $post);

        die(json_encode($result));
    }

    public function executeCabinet(sfWebRequest $request) {
        $this->createData();
        $this->sub = null;
        
        if (is_null($request->getParameter('sort'))) {
            $sort = sbValues::ORDER_SORT_MONTH;
        } else {
            $sort = $request->getParameter('sort');
        }
        
        if (is_null($request->getParameter('page'))) {
            $page = 1;
        } else {
            $page = $request->getParameter('page');
        }
        
        if (is_null($request->getParameter('order'))) {
            $order_id = 0;
        } else {
            $order_id = $request->getParameter('order');
            if ($order_id > 0) {
                $sort = sbValues::ORDER_SORT_ID;
            }
        }
        
        if (is_null($request->getParameter('from')) && is_null($request->getParameter('to'))) {
            $date = array('from_date' => '1970-01-01', 'to_date' => '2125-12-12');
        } else {
            $date = array('from_date' => $request->getParameter('from'), 'to_date' => $request->getParameter('to'));
        }
       
        $my_id = $this->getMyId();
        if ($my_id != 0) {
            $this->user = tblUsersTable::getInstance()->findByDql('id=?', $my_id)->getFirst();
            $cOrders = new sbOrders();
            $this->orders = $cOrders->getMyOrders($my_id, $order_id, $sort, $date, $page);
        } else {
            $this->redirect($request->getReferer());
        }
    }
    
    public function executeCancellation(sfWebRequest $request) {
        $order_id = $request->getPostParameter('order_id');
        
        $orders = new sbOrders();
        $resutl = $orders->cancellationOrder($order_id);
        if ($result['status'] == 'Success') {
            die(json_encode('Cancellation order ' . $order_id . ' was successful.'));
        } else {
            $orders->sendMailCancellationToAgent($order_id);
            die(json_encode('We will notify you when the order will be canceled.'));
        }
    }

    public function executeVaucher(sfWebRequest $request) {
        $this->createData();
        $this->sub = 'Hotels';

        $order_id = $request->getParameter('order');
        $booking = new sbBooking();
        $this->order = $booking->currentBooking($order_id);
    }

    public function executeAgentPage(sfWebRequest $request) {
        $this->createData();
        $this->sub = null;

        $agent_id = $request->getParameter('agent');
        if ($agent_id == $this->getMyId()) {
            $this->edit = true;
        } else {
            $this->edit = false;
        }
        $this->agent_id = $agent_id;
        $aData = tblUsersTable::getInstance()->findByDql('id=?', $agent_id)->getFirst();
        $this->agent = $aData;
        $this->agentCountry = tblCountryTable::getInstance()->findByDql('id=?', $aData->getCountry())->getFirst();
        $this->agentRegion = tblRegionTable::getInstance()->findByDql('id=?', $aData->getRegion())->getFirst();
        $this->agentCity = tblCityTable::getInstance()->findByDql('id=?', $aData->getCity())->getFirst();
        $this->prev = $request->getReferer();
    }

    public function executeAgentEdit(sfWebRequest $request) {
        $this->createData();
        $this->sub = null;

        $agent_id = $request->getParameter('agent');
        $this->agent_id = $agent_id;

        $this->form = new AgentEditForm(array(), array('agent_id' => $agent_id));

        if ($request->isMethod('post')) {
            $values = $request->getPostParameter('agentsedit');
            $agent = new sbAgent();
            $update = $agent->updateAgentData($values);
            if ($update) {
                $this->redirect('agentpage', array('agent' => $agent_id));
            } else {
                $this->redirect('homepage');
            }
        }
    }

    public function createData() {
        $cookie = $this->getRequest()->getCookie('troli');

        if ($cookie) {
            //0 - email, 1 - permissions, 2 - id, 3 - time login to site, 4 - is online(0 false, 1 true) 
            if (self::checkTime($cookie)) {
                $data = base64_decode($cookie);
                $data = explode("/", $data);
                $this->user = sbUser::getUserData($data[2]);
                $this->menu = self::createMenu($data[1]);
            } else {
                $this->user = '0';
                $this->menu = null;
                $this->getResponse()->setCookie("troli", "");
                $this->redirect('homepage');
            }
        } else {
            $this->user = '0';
            $this->menu = null;
        }
    }

    //check if time not over 10 minutes
    public function checkTime($data) {
        if ($data) {
            $data = explode("/", base64_decode($data));
            if ($data[3] + 15 * 60 > time() || $data[4] == 'online') {
                return true;
            }

            return false;
        }

        return false;
    }

    //update time if session is life
    public function updateData($data) {
        if ($data) {
            $data = explode("/", base64_decode($data));
            $data[3] = time();

            $ndata = $data[0] . '/' . $data[1] . '/' . $data[2] . '/' . $data[3];

            return base64_encode($ndata);
        }

        return false;
    }

    public function getPermissions() {
        $cookie = $this->getRequest()->getCookie('troli');

        if (isset($cookie)) {
            $data = explode("/", base64_decode($cookie));

            return $data[1];
        } else {
            return 0;
        }
    }

    public function getMyId() {
        $cookie = $this->getRequest()->getCookie('troli');

        if (isset($cookie)) {
            $data = explode("/", base64_decode($cookie));

            return $data[2];
        } else {
            return 0;
        }
    }

    public function createMenu($permission) {
        if ($permission == sbValues::PERMISSIONS_STANDART) {
            return array(
                array('name' => 'Orders', 'url' => ''),
                array('name' => 'Logout', 'url' => 'logout')
            );
        } else if ($permission == sbValues::PERMISSIONS_AGENT) {
            $agent = $this->getMyId();
            return array(
                array('name' => 'Orders', 'url' => ''),
                array('name' => 'Balance', 'url' => ''),
                array('name' => 'Agent Page', 'url' => 'agentpage', 'agent' => $agent),
                array('name' => 'Logout', 'url' => 'logout')
            );
        } else if ($permission == sbValues::PERMISSIONS_FIRM) {
            return array(
                array('name' => 'Orders', 'url' => ''),
                array('name' => 'Balance', 'url' => ''),
                array('name' => 'Logout', 'url' => 'logout')
            );
        } else if ($permission == sbValues::PERMISSIONS_ADMIN) {
            return array(
                array('name' => 'Orders', 'url' => ''),
                array('name' => 'Balance', 'url' => ''),
                array('name' => 'Admin Panel', 'url' => 'admin'),
                array('name' => 'Logout', 'url' => 'logout')
            );
        }
    }

    public function redirectPreviusPage($request, $current) {
        $url = $this->getContext()->getRequest()->getReferer();
        $url = explode("/", $url);

        if ($url[6] == $current) {
            $this->redirect('homepage');
        } else {
            $this->redirect($request->getReferer());
        }
    }

}
